<?php
/**
 * Author: ChenGuangHui
 * Email：13035809409@163.com
 * Date Time: 2021/4/30 11:35
 */


namespace App\Logic\User;


use App\Enums\HttpCode;
use App\Logic\CommLogic;
use App\Models\Store\CouponUser;;
use App\Models\Store\PointRecord;
use App\Models\Store\User;
use App\Notifications\RegisterNotify;
use Arr;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\QueryException;

class UserLogic extends CommLogic
{
    /**
     * @param $params
     * @return mixed
     */
    public function lists($params)
    {
        $query = User::query()
            ->when(isset($params['status']), function (Builder $query) use ($params) {
                $query->where('status', $params['status']);
            })
            ->when(!empty($params['name']), function (Builder $query) use ($params) {
                $query->where('name', 'like', '%' . $params['name'] . '%');
            });

        if (!empty($sortData)) {
            $query = $query->orderBy($sortData['sortRow'], $sortData['sortType']);
        }else{
            $query = $query->orderBy('uid', 'desc');
        }

        $data = $query->get()->toArray();

        return $data;
    }

    /**
     * @param array $where
     * @param array $pageData
     * @param array $sortData
     * @return \Illuminate\Http\JsonResponse
     */
    public function index($where = [], $pageData = ['pageSize' => 20, 'pageNow' => 1], $sortData = [])
    {
        $query = User::query()
            ->when(isset($where['status']), function (Builder $query) use ($where) {
                $query->where('status', $where['status']);
            })
            ->when(!empty($where['name']), function (Builder $query) use ($where) {
                $query->where('name', '%' . $where['name'] . '%');
            });

        if (!empty($sortData)) {
            $query = $query->orderBy($sortData['sortRow'], $sortData['sortType']);
        }else{
            $query = $query->orderBy('uid', 'desc');
        }

        $data = $query->paginate($pageData['pageSize'], ['*'], 'page', $pageData['pageNow'])
            ->toArray();

        foreach($data["data"] as &$item){
            // $item['avatar_url'] = Arr::first(array_column(json_decode($item['avatar_url'], true), 'url'));
        }

        return $data;
    }

    /**
     * 优惠券列表
     * 
     * @param array $where
     * @param array $pageData
     * @param array $sortData
     * @return \Illuminate\Http\JsonResponse
     */
    public function coupon($where = [], $pageData = ['pageSize' => 20, 'pageNow' => 1], $sortData = [])
    {
        $query = CouponUser::query()
            ->when(isset($where['uid']), function (Builder $query) use ($where) {
                $query->where('uid', $where['uid']);
            })
            ->when(isset($where['status']), function (Builder $query) use ($where) {
                $query->where('status', $where['status']);
            })
            ->when(!empty($where['name']), function (Builder $query) use ($where) {
                $query->where('name', '%' . $where['name'] . '%');
            });

        if (!empty($sortData)) {
            $query = $query->orderBy($sortData['sortRow'], $sortData['sortType']);
        }else{
            $query = $query->orderBy('id', 'desc');
        }

        $data = $query->paginate($pageData['pageSize'], ['*'], 'page', $pageData['pageNow'])
            ->toArray();

        return $data;
    }

    /**
     * 积分列表
     * 
     * @param array $where
     * @param array $pageData
     * @param array $sortData
     * @return \Illuminate\Http\JsonResponse
     */
    public function point($where = [], $pageData = ['pageSize' => 20, 'pageNow' => 1], $sortData = [])
    {
        $query = PointRecord::query()
            ->when(isset($where['uid']), function (Builder $query) use ($where) {
                $query->where('uid', $where['uid']);
            })
            ->when(isset($where['status']), function (Builder $query) use ($where) {
                $query->where('status', $where['status']);
            });

        if (!empty($sortData)) {
            $query = $query->orderBy($sortData['sortRow'], $sortData['sortType']);
        }else{
            $query = $query->orderBy('id', 'desc');
        }

        $data = $query->paginate($pageData['pageSize'], ['*'], 'page', $pageData['pageNow'])
            ->toArray();

        return $data;
    }

    /**
     * @param $params
     * @param $uid
     * @return User|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function show($params, $uid)
    {
        $user = User::query()->where('uid', $uid)->first();
        abort_if(empty($user), HttpCode::FORBIDDEN, '找不到用户');
        $user->coupon = CouponUser::query()->where('uid', $uid)->get();
        return $user;
    }

    /**
     * @param $params
     * @param $uid
     * @return bool
     * @throws \Throwable
     */
    public function update($params, $uid)
    {
        $lockName = 'user_update_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');

        $user = User::query()->where('uid', $uid)->first();
        abort_if(empty($user), HttpCode::FORBIDDEN, '找不到用户');
        \DB::beginTransaction();
        try {
            $data = array(
                'mobile' => $params['mobile'],
                'avatar_url' => $params['avatar_url'] ?? ''
            );
            $user->update($data);
            \DB::commit();
        } catch (QueryException $exception) {
            \DB::rollBack();
            throw new \Exception($exception->getMessage(), $exception->getCode());
        }
        return true;
    }

    /**
     * @param $uid
     * @return bool
     * @throws \Throwable
     */
    public function destroy($uid)
    {
        $data = User::query()->where('uid', $uid)->first();
        abort_unless($data, HttpCode::FORBIDDEN, '找不到用户');
        \DB::beginTransaction();
        try {
            User::query()->where('uid', $uid)->delete();
            # code...

            \DB::commit();
        } catch (QueryException $exception) {
            \DB::rollBack();
            throw new \Exception($exception->getMessage(), $exception->getCode());
        }
        return true;
    }
}
